package cn.kooki.app.duobao.ui.Fragment;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.widget.GridLayoutManager;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextSwitcher;
import android.widget.TextView;
import android.widget.ViewSwitcher;

import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.HashMap;

import butterknife.Bind;
import butterknife.ButterKnife;
import cn.kooki.app.duobao.R;
import cn.kooki.app.duobao.base.BaseFragment;
import cn.kooki.app.duobao.base.BaseRecyclerAdapter;
import cn.kooki.app.duobao.core.MainFactory;
import cn.kooki.app.duobao.data.Bean.Index.BannerItem;
import cn.kooki.app.duobao.data.Bean.Index.BannerResponse;
import cn.kooki.app.duobao.data.Bean.Index.GoodsItem;
import cn.kooki.app.duobao.data.Bean.Index.IndexGoodResponse;
import cn.kooki.app.duobao.data.Bean.Index.NoticeItem;
import cn.kooki.app.duobao.data.Bean.Index.NoticeResponse;
import cn.kooki.app.duobao.data.bus.NetStatusEvent;
import cn.kooki.app.duobao.data.constant.Constants;
import cn.kooki.app.duobao.ui.Activity.Goods.GoodsDetailAcitvity;
import cn.kooki.app.duobao.ui.Activity.Goods.KindActivity;
import cn.kooki.app.duobao.ui.Activity.Goods.SearchActivity;
import cn.kooki.app.duobao.ui.Activity.Goods.SearchResultActivity;
import cn.kooki.app.duobao.ui.Activity.Share.ShareActivity;
import cn.kooki.app.duobao.ui.Activity.Comm.WebViewActivity;
import cn.kooki.app.duobao.ui.Adapter.IndexGridAdapter;

import cn.kooki.app.duobao.ui.view.LoadingProgressView;
import cn.kooki.app.duobao.ui.widget.CustomRelativeLayout;
import cn.kooki.app.duobao.ui.widget.XRecylerView;
import cn.kooki.app.duobao.ui.widget.banner.IndexBannerController;
import cn.kooki.app.duobao.ui.widget.banner.SliderBanner;

import cn.kooki.app.duobao.util.ScreenUtils;

import cn.kooki.app.duobao.util.StringUtils;
import retrofit.Callback;
import retrofit.RetrofitError;
import retrofit.client.Response;

/**
 * Created by xiong on 2015/11/25.
 */
public class IndexFragment extends BaseFragment implements View.OnClickListener, ViewSwitcher.ViewFactory {


    private static final int PAUSE = -1;
    private static final int START = 1;
    RelativeLayout newestLayout;
    TextView left;
    TextView renqi;

    RelativeLayout totalLayout;
    ImageView sortTypeIcon;
    View homeSortInditator;
    TextView totalText;
    @Bind(R.id.top_search)
    ImageButton topSearch;
    @Bind(R.id.action_bar_logo)
    ImageView actionBarLogo;
    @Bind(R.id.action_bar_text)
    TextView actionBarText;
    @Bind(R.id.toolbar)
    RelativeLayout toolbar;
    @Bind(R.id.grid_border)
    ImageView gridBorder;
    @Bind(R.id.notice_span)
    ImageView noticeSpan;
    @Bind(R.id.notice_icon)
    ImageView noticeIcon;
    @Bind(R.id.notice_more)
    ImageView noticeMore;
    @Bind(R.id.notice_text)
    TextView noticeText;
    @Bind(R.id.notice_wrapper)
    RelativeLayout noticeWrapper;

    @Bind(R.id.loadingWrapper)
    CustomRelativeLayout loadingWrapper;
    @Bind(R.id.recycelerView)
    XRecylerView recycelerView;


    private View header;
    private IndexGridAdapter adapter;
    private ArrayList<GoodsItem> goodsItems = new ArrayList<>();
    private int width;
    private boolean isdes = false;
    private boolean isfrist = false;
    private LinearLayout.LayoutParams layoutParams;
    private View networkerror;
    private View index_kind;
    private SliderBanner sliderBanner;
    private int order = 1;
    private int orderby = 1;
    private HashMap<String, String> params;
    private Animation loadinganimation;
    private boolean ischange;
    private int currt_page = 1;
    private LoadingProgressView loadingmoreprogress;
    private TextView loadingmoreText;
    public boolean isLoadingData;
    public boolean loadingMoreEnabled;
    private boolean isnomore;
    private View index_share;
    private IndexBannerController controller;
    private View index_question;
    private View index_ten;
    private TextSwitcher textswitcher;
    private int count = 0;

    private PlayHandler handler = new PlayHandler(this);
    private long lasttime;
    private int length;


    @Override
    public View setView(LayoutInflater inflater, ViewGroup container) {
        View view = inflater.inflate(R.layout.fragment_index, container, false);
        header = inflater.inflate(R.layout.layout_grid_index_header, null);
        newestLayout = (RelativeLayout) header.findViewById(R.id.newest_layout);
        renqi = (TextView) header.findViewById(R.id.renqi);
        totalLayout = (RelativeLayout) header.findViewById(R.id.total_layout);
        totalText = (TextView) header.findViewById(R.id.total_text);
        index_kind = header.findViewById(R.id.rl_index_tab_kind);
        index_share = header.findViewById(R.id.rl_index_tab_share);
        index_question = header.findViewById(R.id.rl_index_tab_qa);
        index_ten = header.findViewById(R.id.rl_index_tab_ten);
        left = (TextView) header.findViewById(R.id.left);
        textswitcher = (TextSwitcher) header.findViewById(R.id.text);
        sortTypeIcon = (ImageView) header.findViewById(R.id.sort_tab_icon4);
        sliderBanner = (SliderBanner) header.findViewById(R.id.slider);
        ButterKnife.bind(this, view);
        return view;
    }

    private ArrayList<BannerItem> urls = new ArrayList<>();


    @Override
    public void afterView() {

        renqi.setSelected(true);
        loadingWrapper.setIswhitle(true);
        GridLayoutManager gridLayoutManager = getGridLayoutManager(2);
        adapter = new IndexGridAdapter(context);
        adapter.setOnItemClickListener(new BaseRecyclerAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(int position, Object data) {
                GoodsItem item = (GoodsItem) data;
                HashMap<String, String> params = new HashMap<String, String>();
                params.put("id", item.getId());
                params.put("qishu", item.getQishu());
                intent(GoodsDetailAcitvity.class, params);
            }
        });
        recycelerView.addHeaderView(header);
        recycelerView.setLayoutManager(gridLayoutManager);
        recycelerView.setAdapter(adapter);
        renqi.setOnClickListener(this);
        newestLayout.setOnClickListener(this);
        left.setOnClickListener(this);
        totalLayout.setOnClickListener(this);
        index_kind.setOnClickListener(this);
        index_share.setOnClickListener(this);
        index_ten.setOnClickListener(this);
        index_question.setOnClickListener(this);

        params = new HashMap<>();


        recycelerView.setLoadingListener(new XRecylerView.LoadingListener() {
            @Override
            public void onRefresh() {
                getdata(false);
            }

            @Override
            public void onLoadMore() {
                getdata(true);
            }
        });

        loadingWrapper.setRetryClickListener(new CustomRelativeLayout.onRetryClickListener() {
            @Override
            public void onRetry() {
                if (loadingWrapper.isShowNetError()) loadingWrapper.hideNetError();
                beginRefresh();
            }
        });

        topSearch.setOnClickListener(this);

        int width = ScreenUtils.getScreenWidth(context);
        LinearLayout.LayoutParams layoutParams = (LinearLayout.LayoutParams) sliderBanner.getLayoutParams();
        float radio = Constants.banner_radio;
        layoutParams.height = (int) (width * radio);
        sliderBanner.setLayoutParams(layoutParams);
        controller = new IndexBannerController(sliderBanner, context);
        recycelerView.setLoadingMoreEnabled(true);
        controller.setBannerItemClickListenter(new IndexBannerController.BannerItemClickListenter() {
            @Override
            public void OnItemClick(View view, int postion) {
                if (urls.size() > 0) {
                    BannerItem bannerItem = urls.get(postion);
                    if (bannerItem.type == 1) {

                    } else if (bannerItem.type == 2) {
                        HashMap<String, String> params = new HashMap<String, String>();
                        params.put("id", bannerItem.id);
                        params.put("qishu", bannerItem.qishu);
                        intent(GoodsDetailAcitvity.class, params);
                    }
                }
            }
        });


        loadTextSwitcher();
        getnotice();
        beginRefresh();
    }

    private void loadTextSwitcher() {
        textswitcher.setFactory(this);
        Animation in = AnimationUtils.loadAnimation(context, R.anim.pop_up_in);
        Animation out = AnimationUtils.loadAnimation(context, R.anim.notice_out);
        textswitcher.setInAnimation(in);
        textswitcher.setOutAnimation(out);

    }

    private static class PlayHandler extends Handler {
        private static final long NOTICE_CHANGE_TIME = 5000;
        private final WeakReference<IndexFragment> mFragment;

        public PlayHandler(IndexFragment fragment) {
            mFragment = new WeakReference<IndexFragment>(fragment);
        }

        @Override
        public void handleMessage(Message msg) {

            if (mFragment.get() == null) {
                return;
            }
            if (msg.what == START && mFragment.get().noticeItems.size() > 0) {
                if (mFragment.get().textswitcher != null) {
                    NoticeItem noticeItem = mFragment.get().noticeItems.get(mFragment.get().count);
                    mFragment.get().textswitcher.setText("恭喜" + noticeItem.q_user + "获得" + noticeItem.title);
                    mFragment.get().count++;
                    if (mFragment.get().count == mFragment.get().noticeItems.size() - 1) {
                        mFragment.get().count = 0;
                        mFragment.get().handler.sendEmptyMessageDelayed(START, NOTICE_CHANGE_TIME);
                    } else {
                        mFragment.get().handler.sendEmptyMessageDelayed(START, NOTICE_CHANGE_TIME);
                    }
                }
            }
        }
    }


    private ArrayList<NoticeItem> noticeItems = new ArrayList<>();

    private void getnotice() {

        MainFactory.getApiInstance().noticelist(new Callback<NoticeResponse>() {
            @Override
            public void success(NoticeResponse baseResponse, Response response) {
                if (baseResponse.data != null) {
                    handler.removeMessages(START);
                    noticeItems.clear();
                    noticeItems.addAll(baseResponse.data);
                    handler.sendEmptyMessage(START);
                }
            }

            @Override
            public void failure(RetrofitError error) {

            }
        });
    }

    private void beginRefresh() {

        if (recycelerView != null) {
            getimgs();
            recycelerView.postDelayed(new Runnable() {
                @Override
                public void run() {
                    recycelerView.autoRefresh(false);
                }
            }, 500);
        }
    }


    public void getimgs() {
        MainFactory.getApiInstance().bannerurls(new Callback<BannerResponse>() {
            @Override
            public void success(BannerResponse bannerResponse, Response response) {
                if (bannerResponse.data != null) {
                    urls.clear();
                    urls.addAll(bannerResponse.data);
                    controller.play(urls);
                }
            }

            @Override
            public void failure(RetrofitError error) {
                error.getKind();
            }
        });
    }

    public void getdata(final boolean isloadmore) {
        lasttime = System.currentTimeMillis();
        if (isloadmore) {
            currt_page++;

        } else {
            currt_page = 1;
        }
        HashMap<String, Object> other = new HashMap<>();
        other.put("order", order);
        other.put("orderby", orderby);
        MainFactory.getApiInstance().goodRespone(currt_page, other, new Callback<IndexGoodResponse>() {
            @Override
            public void success(IndexGoodResponse indexGoodResponse, Response response) {
                safeRefreshView(indexGoodResponse, response, isloadmore);
            }

            @Override
            public void failure(RetrofitError error) {
                safeRefreshError(error, isloadmore);
            }
        });
    }

    private void safeRefreshError(RetrofitError error, boolean isloadmore) {
        if (loadingWrapper != null) {
            if (error.getKind() == RetrofitError.Kind.NETWORK) {
                loadingWrapper.showNetError();
                recycelerView.restMoreLoading();
            }
            hideloading(isloadmore);
            isLoadingData = false;
            if (isloadmore) {
                recycelerView.loadMoreComplete();
            }
        }
    }

    private void safeRefreshView(IndexGoodResponse indexGoodResponse, Response response, boolean isloadmore) {
        hideloading(isloadmore);
        if (loadingWrapper != null) {

            if (isloadmore) {
                adapter.addDatas(indexGoodResponse.getData());
                if (indexGoodResponse.getData().size() == Constants.DEFAULT_COUNT) {
                    recycelerView.loadMoreComplete();
                } else {
                    recycelerView.noMoreLoading();
                }
            } else {
                adapter.mDatas.clear();
                adapter.addDatas(indexGoodResponse.getData());
                recycelerView.restMoreLoading();
            }
        }
    }


    public void hideloading(boolean isloadmore) {
        if (loadingWrapper != null) {
            recycelerView.refreshComplete();
            loadingWrapper.hideloading();
        }
    }

    @Override
    public void onEventMainThread(NetStatusEvent netStatusEvent) {
        super.onEventMainThread(netStatusEvent);
        if (networkerror == null) {
            networkerror = LayoutInflater.from(context).inflate(R.layout.error_network, loadingWrapper, false);

            loadingWrapper.addView(networkerror);
            networkerror.setVisibility(View.VISIBLE);
        } else {
            networkerror.setVisibility(View.VISIBLE);
        }

    }


    /**
     * 获取数据
     */
    public void getresult() {
        recycelerView.getRecyclerView().scrollToPosition(0);
        loadingWrapper.showloading();
        getdata(false);
    }

    /**
     * 选择排序和类型
     */
    public void switchSort() {
        totalText.setSelected(false);
        sortTypeIcon.setSelected(false);
        renqi.setSelected(false);
        newestLayout.setSelected(false);
        left.setSelected(false);
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.unbind(this);
    }


    /**
     * 点击事件
     *
     * @param v
     */
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.total_layout:
                switchSort();
                totalText.setSelected(true);
                isdes = !isdes;
                sortTypeIcon.setSelected(isdes);
                if (!isdes) {
                    orderby = 1;
                } else {
                    orderby = 2;
                }

                order = 4;
                ischange = true;
                getresult();
                break;
            case R.id.renqi:
                switchSort();
                order = 1;
                isdes = false;
                renqi.setSelected(true);
                sortTypeIcon.setSelected(false);
                getresult();
                break;
            case R.id.newest_layout:
                switchSort();
                sortTypeIcon.setSelected(false);
                order = 2;
                isdes = false;
                getresult();
                newestLayout.setSelected(true);
                break;
            case R.id.left:
                switchSort();
                sortTypeIcon.setSelected(false);
                order = 3;
                isdes = false;
                getresult();
                left.setSelected(true);
                break;
            case R.id.rl_index_tab_kind:
                intent(KindActivity.class);
                break;
            case R.id.top_search:
                intent(SearchActivity.class);
                break;
            case R.id.rl_index_tab_share:
                intent(ShareActivity.class);
                break;
            case R.id.rl_index_tab_ten:
                HashMap<String, String> param = new HashMap<>();
                param.put("title", "10元专区");
                param.put("type", "10");
                intent(SearchResultActivity.class, param);
                break;
            case R.id.rl_index_tab_qa:
                HashMap<String, Object> parma = new HashMap<>();
                parma.put("title", "常见问题");
                parma.put("type", WebViewActivity.QUESTION_TYPE);
                intent2(WebViewActivity.class, parma);
                break;
        }
    }

    @Override
    public void onPause() {
        super.onPause();
        handler.removeMessages(START);
    }

    @Override
    public void onResume() {
        super.onResume();
        handler.sendEmptyMessage(START);
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if (isVisibleToUser) {
            long currentTimeMillis = System.currentTimeMillis();
            if (currentTimeMillis - lasttime > 1000 * 60 * 1000) {
                if (recycelerView != null) {
                    recycelerView.autoRefresh(false);
                    getnotice();
                }
            }

            checkNeedUpadte();
        }
    }

    private void checkNeedUpadte() {

    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        // TODO: inflate a fragment view
        View rootView = super.onCreateView(inflater, container, savedInstanceState);
        ButterKnife.bind(this, rootView);
        return rootView;
    }

    @Override
    public View makeView() {
        TextView textView = new TextView(context);
        textView.setSingleLine();
        textView.setGravity(Gravity.CENTER_VERTICAL);
        textView.setEllipsize(TextUtils.TruncateAt.END);
        FrameLayout.LayoutParams layoutParams = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
        textView.setLayoutParams(layoutParams);
        textView.setTextSize(12);
        return textView;
    }
}
